package com.yiyi.user.component;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.internal.util.WebUtils;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.google.zxing.WriterException;
import com.yiyi.user.config.AlipayConfig;
import com.yiyi.user.model.AliPayModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;

/**
 * 支付宝支付 模板
 */
@Slf4j
@Data
@Component
public class AliPayTemplate {

    @Autowired
    private AlipayConfig alipayProperties;

    private AlipayClient alipayClient;

    @PostConstruct
    public void init() {

        // 1. 根据支付宝的配置生成一个支付客户端
        alipayClient = new DefaultAlipayClient(
                alipayProperties.getGatewayUrl(),
                alipayProperties.getAppId(),
                alipayProperties.getAppPrivateKey(),
                "json",
                alipayProperties.getCharset(),
                alipayProperties.getAlipayPublicKey(),
                alipayProperties.getSignType()
        );
    }

    public String genAliPayPicture(AliPayModel parModel) throws AlipayApiException, IOException, WriterException {
        AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
        // 强制关闭 ssl 证书校验
        WebUtils.setNeedCheckServerTrusted(false);
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("out_trade_no",parModel.getOutTradeNo());// 商户订单号
        jsonObject.put("total_amount",parModel.getTotalAmount());// 商品价格
        jsonObject.put("subject",parModel.getSubject());// 商品标题
        jsonObject.put("store_id",parModel.getStoreId());//组织或公司名
//        jsonObject.put("timeout_express","5m");// 订单有效时间
//        jsonObject.put("returnUrl", parModel.getReturnUrl());
//        jsonObject.put("notifyUrl", parModel.getNotifyUrl());
        alipayRequest.setReturnUrl(parModel.getReturnUrl());

        alipayRequest.setBizContent(jsonObject.toString());
        String qrCode ="";
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(alipayRequest);

            if (response.isSuccess()) {
                // 生成二维码并返回给前端
                qrCode = response.getQrCode();
                System.out.println("创建订单结果:" + response.getBody());
                System.out.println("订单编号是" + response.getOutTradeNo());
            }
        }catch (Exception e){
            System.out.println("出现异常:" + e.getMessage());
        }

        return qrCode;
    }


    /**
     *
     */
    public String aliPay(AliPayModel parModel) throws
            AlipayApiException, IOException, WriterException, SignatureException,
            NoSuchAlgorithmException, InvalidKeyException {

        AlipayTradePayModel model=new AlipayTradePayModel();
        model.setOutTradeNo(parModel.getOutTradeNo());
        // 设置订单金额
        model.setTotalAmount(parModel.getTotalAmount());
        // 订单名字
        model.setSubject(parModel.getSubject());
        model.setProductCode(parModel.getProductCode());

        // 设置请求参数
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        //页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(parModel.getReturnUrl());
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(parModel.getNotifyUrl());
        // 设置参数
        alipayRequest.setBizModel(model);


        String qrCode = "";
        try {
            qrCode= alipayClient.pageExecute(alipayRequest).getBody();
        }catch (Exception e){

        }
        return qrCode;
    }

}
